package com.mocai.merchant.controller;

import com.mocai.merchant.model.Menu;
import com.mocai.merchant.model.User;
import com.mocai.merchant.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/1/8.
 */
@Controller
public class MenuController {

    @Autowired
    MenuService menuService;

    @RequestMapping("/menu")
    public String toMenu() {
        return "demo/ztree/menu";
    }

    @RequestMapping(value = "/menus", method = RequestMethod.GET)
    @ResponseBody
    public Object doGetAllMenus(HttpServletRequest request) {
        Map<Object, Object> returnValue = new LinkedHashMap<>();
        List<Menu> menus = menuService.findAll();
        returnValue.put("menus", menus);
        return returnValue;
    }

    @RequestMapping(value = "/user/menus", method = RequestMethod.GET)
    @ResponseBody
    public Object doGetUserMenus(HttpServletRequest request) {
        Map<Object, Object> returnValue = new LinkedHashMap<>();
        // 所有菜单
        List<Menu> allMenus = menuService.findAll();
        returnValue.put("allMenus", allMenus);
        // 用户菜单
        User user = (User) request.getSession().getAttribute("user");
        Integer userId = user.getId();
        List<Menu> userMenus = menuService.findByUserId(userId);
        returnValue.put("userMenus", userMenus);
        return returnValue;
    }

    @RequestMapping(value = "/user/menus", method = RequestMethod.POST)
    @ResponseBody
    public Object doSaveUserMenus(HttpServletRequest request, @RequestParam("menuIds[]") Integer[] menuIds) {
        Map<Object, Object> returnValue = new LinkedHashMap<>();
        User user = (User) request.getSession().getAttribute("user");
        Integer userId = user.getId();
        // 删除
        menuService.deleteUserMenus(userId);
        // 新增
        if(null != menuIds){
            menuService.addUserMenus(userId, menuIds);
        }
        return returnValue;
    }

}
